package com.laicunba.ext.web.controller.h5.activity;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.time.DateUtils;
import org.json.simple.JSONArray;
import org.json.simple.parser.JSONParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.laicunba.ext.service.SlaveActivityJoinService;
import com.laicunba.ext.service.SlaveUserService;
import com.laicunba.ext.web.annotation.ResponseCache;
import com.laicunba.ext.web.controller.BaseController;
import com.laicunba.pojo.ActivityDO;
import com.laicunba.pojo.RegistryDO;
import com.laicunba.service.ActivityService;
import com.laicunba.service.RegistryService;
import com.laicunba.util.StringUtil;

@ResponseCache(time = 10)
@Controller
@RequestMapping(value = "/h5/ext/activity")
public class GainGoldInviteDataController extends BaseController {
	@Autowired
	private SlaveUserService slaveUserService;
	@Autowired
	private ActivityService activityService;

	@Autowired
	private RegistryService registryService;

	@RequestMapping(value = "/getGainGoldInviteData.htm")
	public ModelAndView getGainGoldInviteData() {
		ModelAndView view = new ModelAndView();
		view.setViewName("getGainGoldInviteData.jsp");
		// 英雄榜
		try {

			ActivityDO activity = activityService.get(ActivityDO.class, "20170410");
			DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			if (activity != null) {
				Map<String, Object> tempMap = null;
				List<Map<String, Object>> inviteRankList = slaveUserService.findInviteRankList(sdf.format(activity.getBeginTime()), sdf.format(DateUtils.addDays(activity.getEndTime(), 1)), 5);
				RegistryDO registry = registryService.get(RegistryDO.class, "sys.act.data.20170410");
				if (inviteRankList != null && registry != null && StringUtil.isNotEmpty(registry.getVal())) {
					JSONArray registryInviteArray = (JSONArray) new JSONParser().parse(registry.getVal());
					if (registryInviteArray != null && registryInviteArray.size() > 0) {
						for (int i = 0; i < registryInviteArray.size(); i++) {
							tempMap = (Map<String, Object>) registryInviteArray.get(i);
							inviteRankList.add(tempMap);
						}
						Collections.sort(inviteRankList, new Comparator<Map<String, Object>>() {
							public int compare(Map<String, Object> m1, Map<String, Object> m2) {
								if (Integer.valueOf(String.valueOf(m1.get("invite_count"))).compareTo(Integer.valueOf(String.valueOf(m2.get("invite_count")))) > 0) {
									return -1;
								} else {
									return 1;
								}
							}
						});
					}
				}
				view.addObject("inviteRankList", inviteRankList);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return view;
	}
}
